/**   
* @Title: RedissonTestCase.java
* @Package me.cloud
* @Description: TODO
* @author xaoyaoyao
* @date Jan 10, 2019 1:23:52 PM
* @version V1.0   
*/
package me.cloud;

import java.util.concurrent.TimeUnit;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.test.context.junit4.SpringRunner;

/**
 * @ClassName: RedissonTestCase
 * @Description: TODO
 * @author xaoyaoyao
 * @date Jan 10, 2019 1:23:52 PM
 * 
 */
@RunWith(SpringRunner.class)
@SpringBootTest(classes = { DistributedLockApplication.class }) // 指定启动类
public class RedissonTestCase {

	private static final String LOCK_TITLE = "redisLock_";

	@Autowired
	private StringRedisTemplate redisTemplate;

	@Autowired
	private RedissonClient redisson;

	public void acquire(String lockName) {
		String key = LOCK_TITLE + lockName;
		RLock mylock = redisson.getLock(key);
		mylock.lock(60, TimeUnit.MINUTES); // lock提供带timeout参数，timeout结束强制解锁，防止死锁
		System.err.println("======lock======" + Thread.currentThread().getName());
	}

	public void release(String lockName) {
		String key = LOCK_TITLE + lockName;
		RLock mylock = redisson.getLock(key);
		mylock.unlock();
		System.err.println("======unlock======" + Thread.currentThread().getName());
	}

	@Test
	public void testRedisLock() {
		for (int i = 0; i < 100; i++) {
			Thread t = new Thread(new Runnable() {
				@Override
				public void run() {
					try {
						String key = "test123";
						acquire(key);
						Thread.sleep(1000); // 获得锁之后可以进行相应的处理
						System.err.println("======获得锁后进行相应的操作======");
						release(key);
						System.err.println("=============================");
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			});
			t.start();
		}
	}

}
